package com.surveypark.struts2.action;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.interceptor.SessionAware;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.surveypark.domain.User;
import com.surveypark.service.RightService;
import com.surveypark.service.UserService;
import com.surveypark.util.DataUtil;

@Controller("loginAction")
@Scope("prototype")
public class LoginAction extends BaseAction<User> implements SessionAware{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4112033530866374974L;

	@Resource(name="userService")
	private UserService userService;
	private Map<String, Object>	sessionMap;
	
	@Resource(name="rightService")
	private RightService rightService;
	
	@SkipValidation
	public String toLoginPage(){
		return "loginPage";
	}
	
	@SkipValidation
	public String toIndexPage(){
		return "indexPage";
	}
	
	@SkipValidation
	public String toHeaderPage(){
		return "headerPage";
	}
	
	public String doLogin(){
		return SUCCESS;
		
	}
	
	/**
	 * 退出系统
	 */
	@SkipValidation
	public String exit(){
		if(this.sessionMap.get("user") != null){
			this.sessionMap.remove("user");//将user从session中移除
		}
		return "loginPage";
	}
	@Override
	public void validate() {
		
		User u = userService.validateLogin(model.getEmail(), DataUtil.MD5Encrypt(model.getPassword()));
		if(null == u){
			addActionError("用户不存在");
		}else{
			
			//TODO 计算用户权限总和
			int maxRightPos = rightService.getMaxRightPos();
			u.setRightSum(new long[maxRightPos + 1]);
			u.calculateRightSum();
			
			this.sessionMap.put("user", u);//将User放置到session的范围中
		}
	}

	@Override
	public void setSession(Map<String, Object> arg0) {
		this.sessionMap = arg0;
	}
}
